package gac.helloworld;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class MapHandler {

	private static double currLat;
	private static double currLng; 
	private int timeToDestination;
	private String finalDestination;
	private int mHour, mMinute, mDay, mMonth, mYear;
	private int bufferTime;
	private static Activity activity;
	private static LocationListener locationListener;
	private static final String PLACES_AUTOCOMPLETE_URL = "https://maps.googleapis.com/maps/api/place/autocomplete/json?";
	private static final String API_KEY = "ADD THE KEY HERE";

	public MapHandler()
	{
		
	}
	
	public MapHandler(Activity a){
		this.findCurrentLocation(a);
	}
	
	public MapHandler(Activity a, String destination, int hour, int minute, int month, int day, int year, int buffer){
		activity = a;
		finalDestination = destination;
		mHour = hour;
		mMinute = minute;
		mMonth = month;
		mDay = day;
		mYear = year;
		bufferTime = buffer;
		timeToDestination = 0;
		Log.v("",month+"/"+day+"/"+year+" "+hour+":"+minute);
		this.findCurrentLocation(a);
	}

	public static void findCurrentLocation(Activity a){
		// Acquire a reference to the system Location Manager
		if(locationListener==null){
			LocationManager locationManager = (LocationManager) a.getSystemService(Context.LOCATION_SERVICE);
			// Define a listener that responds to location updates
			locationListener = new LocationListener() {
				public void onLocationChanged(Location location) {
					Log.v("", "Latitude = "+location.getLatitude());
					Log.v("", "Longitude = "+location.getLongitude());
					currLat = location.getLatitude();
					currLng = location.getLongitude();
			}

				public void onStatusChanged(String provider, int status, Bundle extras) {}

				public void onProviderEnabled(String provider) {}

				public void onProviderDisabled(String provider) {}
			};

			// Register the listener with the Location Manager to receive location updates
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
		}
	}
	
	//To be used when timeToDestination was just calculated
	public int getTimeToDestination() {
		return timeToDestination;
	}

	//returns the time to the destination from the current location
	public int calculateTime() {
		Log.v("","Calculating Time to Destination");
		Log.v("","Lat = "+currLat+", Long = "+currLng+ ", Desination = " + finalDestination);
		String urlString = "http://maps.googleapis.com/maps/api/directions/json?origin="
			+ currLat
			+ ","
			+ currLng
			+ "&destination="
			+ finalDestination
			+ "&sensor=true";
		String result = "";
		Log.v("","URLSTRING = "+urlString);
		try {
			URL mapURL = new URL(urlString);
			URI uri = new URI(mapURL.getProtocol(), mapURL.getHost(), mapURL.getPath(), mapURL.getQuery(), null);
			HttpClient hc = new DefaultHttpClient();
			HttpGet get = new HttpGet(uri);
			HttpResponse rp = hc.execute(get);
			if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(rp.getEntity());
			}
			
			if(result.length() > 1000){
				
				result = result.substring(0,1000);
				String[] values = result.split("\"value\" : ");
				Scanner scan = new Scanner(values[2]);
				timeToDestination = scan.nextInt();
			}
			else{
				Log.v("URL", urlString);
				Log.v("result", result);
				
			}
			Log.v("Time to destination","Time To destination "+ timeToDestination);
			//System.out.println(currentTime);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//Log.v("Time to destination", "Time to Destination"+timeToDestination);
		return timeToDestination;
	}
	
	//returns true if it's time to leave
	public boolean isTimeToLeave()
	{
		Calendar currDate = Calendar.getInstance();
		String sDate = currDate.get(Calendar.MONTH)
		+ "/" + currDate.get(Calendar.DAY_OF_MONTH) 
		+ "/" + currDate.get(Calendar.YEAR)
		+ " " + currDate.get(Calendar.HOUR_OF_DAY) 
		+ ":" + currDate.get(Calendar.MINUTE);
		Log.v("","Current Date = "+sDate);
		long currSeconds = currDate.getTimeInMillis() / 1000;
		Log.v("","Current Seconds = "+currSeconds);
		Log.v("","End Date = "+mMonth+"/"+mDay+"/"+mYear+" "+mHour+":"+mMinute);
		Calendar endDate = Calendar.getInstance();
		endDate.set(mYear, mMonth, mDay, mHour, mMinute);
		long endSeconds = endDate.getTimeInMillis() / 1000;
		Log.v("","End Seconds = "+endSeconds);
		long timeDiff = endSeconds - currSeconds;
		Log.v("","Time Diff = "+timeDiff);
		long timeUntilLeave = timeDiff - bufferTime - this.calculateTime();
		Log.v("","Time Until Leave = "+timeUntilLeave);
		return timeUntilLeave <= 0;
	}
	
	public boolean shouldCheckTime()
	{
		return true;
	}
	
	public boolean at00()
	{
		return (currLat == 0 && currLng == 0);
	}
	
	public int calculateTravelTime()
	{
		return 0;
	}
	
	public ArrayList<String> getAutocomplete(String input) {
		String urlString = PLACES_AUTOCOMPLETE_URL+"input="+input+"&sensor=true"+"&key="+API_KEY+"&location="+currLat+","+currLng+"&offset=3";
		String result = "";
		ArrayList<String> suggestions = new ArrayList<String>();
		try {
			URL autocompleteURL = new URL(urlString);
			URI uri = new URI(autocompleteURL.getProtocol(), autocompleteURL.getHost(), autocompleteURL.getPath(), autocompleteURL.getQuery(), null);
			HttpClient hc = new DefaultHttpClient();
			HttpGet get = new HttpGet(uri);
			HttpResponse rp = hc.execute(get);
			if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(rp.getEntity());
			}
			String[] values = result.split("\"description\" : ");
			String print = "";
			for(int i=1; i<values.length; i++)
			{
				Scanner scan = new Scanner(values[i]);
				String suggestion = scan.nextLine().trim();
				try{
					suggestions.add(suggestion.substring(1, suggestion.length()-2));
				}catch(StringIndexOutOfBoundsException e){
					suggestions.add(suggestion);
				}
				//suggestions.add(suggestion.substring(1, suggestion.length()-2));
				//suggestions.add(suggestion);
				//suggestions.add(scan.nextLine());
				//print += s + "\n";
			}
			for(String s : suggestions){
				print += s + "\n";
			}
			Log.v("", print);
			//Scanner scan = new Scanner(values[2]);
			//timeToDestination = scan.nextInt();
			//System.out.println(currentTime);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return suggestions;
	}
	
	//checks if string is a valid location
	public boolean isValidLoc(String loc){
		return true;
	}
	
}
